package cn.lxs.web.servlet;

import com.sun.jdi.InconsistentDebugInfoException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/ResponseCodeServlet")
public class ResponseCodeServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建一共画图的对象来搞验证码
        int width = 100;
        int height = 50;
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);

        //美化图片
        //填充颜色
        Graphics g = image.getGraphics();
        //画笔对象
        g.setColor(Color.PINK);
        //设置画笔颜色
        g.fillRect(0,0,width,height);
        //填充颜色

        //画边框
        g.setColor(Color.blue);
        g.drawRect(0,0,width-1,height-1);

        String str = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm0123456789";
        //这里保存随机数
        Random ran = new Random();
        g.setColor(Color.blue);
        StringBuilder sb = new StringBuilder();

        //定义一个变量来存放验证码
        for (int i = 1; i < 5; i++) {
            int index = ran.nextInt(str.length());
            char c = str.charAt(index);
            //画乱码
            sb.append(c);
            g.drawString(c+"",width*i/5,height/2);
        }
        String checkCode_see = sb.toString();
        //将验证码上传
        req.getSession().setAttribute("checkCode_see",checkCode_see);


        //画干扰线
        g.setColor(Color.GREEN);
       /* g.drawLine(1,1,30,30);*/
        for (int i = 0; i < 10; i++) {
            int x1 = ran.nextInt(width);
            int x2 = ran.nextInt(width);
            int y1 = ran.nextInt(height);
            int y2 = ran.nextInt(height);
            g.drawLine(x1,x2,y1,y2);
        }


        //输出图片
        ImageIO.write(image,"jpg",resp.getOutputStream());

    }
}
